class Page < ActiveRecord::Base
  MAX_VALUE = 1000000000000
  validates_presence_of :title
  def validate
    unless read_attribute(:directory)
      errors.add(:file, "File can't be blank and must be a jpg/gif/png")
    end
  end

  def file
  end

  def file=(file)
     add_file(file, 'file0')
  end

  def file1
  end

  def file1=(file1)
    add_file(file1, 'file1')
  end

  def files
    Dir.entries(fullpath(read_attribute(:directory))).reject do |ent|
      ent[0..0] == '.'
    end
  end

  def add_file(file, filegbn)
    return if file.length == 0
    puts 'file_gbn:' + filegbn
    puts 'file_original_filename:' + file.original_filename
    return unless /^image\/(p?jpeg|gif|(x-)?png)$/i.match(file.content_type.strip)
    dir = read_attribute(:directory) || new_directory
    File.open("#{fullpath(dir)}/#{file.original_filename}", 'wb') do |f|
      f.write(file.read)
    end
  end

  def new_directory
    begin
      dir = rand(MAX_VALUE).to_s
      Dir.mkdir(fullpath(dir))
      write_attribute(:directory, dir)
    rescue Error::EEXIST
      dir = nil
    end until dir
    dir
  end

  def fullpath(dir)
    "#{RAILS_ROOT}/public/#{dir}"
  end

  def destroy
    files.each do |file|
      File.delete("#{fullpath(read_attribute(:directory))}/#{file}")
    end
    Dir.delete(fullpath(read_attribute(:directory)))
    super
  end
end
